package com.server.config;

import com.server.Netty.handler.FrameDataHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebSocketStartConfig extends ChannelInitializer<SocketChannel> {

    @Autowired
    NettyAndWebSocketConfig nWConfig;

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        socketChannel.pipeline()
                // 使用Http编解码器
                .addLast(new HttpServerCodec())
                // 添加ChunkedWriteHandler处理器,用于处理大文件
                .addLast(new ChunkedWriteHandler())
                // 将多次请求的数据聚合起来
                .addLast(new HttpObjectAggregator(nWConfig.getAggregator()))
                .addLast(new WebSocketFrameAggregator(nWConfig.getAggregator()))
                // 访问地址以及将http协议升级为ws协议,并且设置内容，以及最重要的数据包大小(maxFrameSize)
                .addLast(new WebSocketServerProtocolHandler(nWConfig.getPath(),"",false,
                        1024*1024*10,false,false,true,1000))
                // WebSocket处理器,对事件进行分发和处理
                .addLast(new FrameDataHandler());

    }
}
